/* 
 * File:   main.c
 * Author: eoe2005
 *
 * Created on 2012年9月11日, 下午11:10
 */


#include "Server.h"
S_Action *Actions;
char *server_host = "127.0.0.1";
int server_tcp_fd,epoll_fd,event_s;
struct epoll_event ev, events[MAX_EVENTS];

int main(int argc, char** argv) {
    int i = 0;
    int clen;
    //daemon(1,1);
    server_tcp_fd = tcp_listen(server_host,SERVER_PORT);
    Actions = init_actions();
    epoll_fd = epoll_create(MAX_EVENTS);
    printf("listened\n");
    
    printf("create epoll_fd\n");
    if(epoll_fd == -1){
        printf("epolnetl error\n");
        exit(-4);
    }
    printf("create epoll_fd\n");
    ev.events = EPOLLIN;
    ev.data.fd = server_tcp_fd;
    if(epoll_ctl(epoll_fd,EPOLL_CTL_ADD,server_tcp_fd,&ev) == -1) {
        printf("epoll set error\n");
        exit(-5);
    }
    printf("start\n");
    while(1){
        event_s = epoll_wait(epoll_fd,events,MAX_EVENTS,-1);
        if(event_s == -1){
            exit(-6);
        }
        for(i = 0 ; i < event_s ; i++){
            if(events[i].data.fd == server_tcp_fd){
                struct sockaddr_in client_addr;
                int cfd = accept(server_tcp_fd,(struct sockaddr *)&client_addr,&clen);
                if(cfd){
                    setnonblocking(cfd);
                    ev.events = EPOLLIN | EPOLLET ;
                    ev.data.fd = cfd;
                    if(epoll_ctl(epoll_fd,EPOLL_CTL_ADD,cfd,&ev) == -1){
                        exit(-7);
                    }
                }  
            }else if(events[i].events & EPOLLIN){
                ev.data.fd = events[i].data.fd;
                char line[1024];
                read(events[i].data.fd,line,1024);
                printf("INPUT:%s\n",line);
                ev.events = EPOLLOUT | EPOLLET;
                epoll_ctl(epoll_fd,EPOLL_CTL_MOD,events[i].data.fd,&ev);
            }else if(events[i].events & EPOLLOUT){
                ev.data.fd = events[i].data.fd;
                ev.events = EPOLLIN | EPOLLET;
                if(Actions->isload){
                    Actions->func(events[i]);
                }else{
                        write(events[i].data.fd,"ni hao a",12);
                }
                epoll_ctl(epoll_fd,EPOLL_CTL_MOD,events[i].data.fd,&ev);
            }
        }
    }
    
    return (EXIT_SUCCESS);
}

